package com.tanhua.dubbo.server.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author: JinboYang
 * @Description:
 * @Date: Created in 下午 14:22 2021/1/11
 * @ModifiedBy:
 */
@Service
public class IdService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public Long createdId(String type, String objectId) {

        type = StringUtils.upperCase(type);

        String hashKey = "TANHUA_ID_HASH_" + type;
        //如果存在objectid 话就返回相应的id
        if (this.redisTemplate.hasKey(hashKey)) {
            return Long.valueOf(this.redisTemplate.opsForHash().get(hashKey, objectId).toString());
        }
        String key = "TANHUA_ID_" + type;
        Long id = this.redisTemplate.opsForValue().increment(key);

        //将生成的id写入redis中
        this.redisTemplate.opsForHash().put(hashKey, objectId, id);
        return id;
    }
}
